import { useEffect, useRef, useState } from 'react';
import React from 'react';
import { Button, Divider,  message,  Modal,  Space,  Table, Tag } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import type { CompanyList } from '../../types';
import { delCompanyItemApi, getCompanyListApi } from '../../api';
import dayjs from 'dayjs';
import DrawerItem from './Components/DrawerItem';

// class CompanyList extends React.Component {
  
//   render() {
//     return <div>Company List
//       <Button type="primary">Antd Button</Button>
//     </div>;
//   }
// }

const CompanyList: React.FC = () => {
  // let isDrawerVisible = false
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  
  const [companyItem,setCompanyItem] = useState<CompanyList>()
  // 2️⃣ 处理打开/关闭抽屉的方法
  const handleOpenDrawer = (row:CompanyList) => {
    // isDrawerVisible = !isDrawerVisible
    setCompanyItem(row)
    setIsDrawerVisible(true);
    // console.log('按了',isDrawerVisible)
  };

  const handleCloseDrawer = () => {
    // isDrawerVisible = false
    setIsDrawerVisible(false);
    // setCompanyItem(null)
  };

  const columns: TableColumnsType<CompanyList> = [
    {
      title: '公司名称',
      dataIndex: 'name',
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: '账户',
      dataIndex: 'account',
    },
    {
      title: '银行支行',
      dataIndex: 'bank_name',
    },
    {
      title: '是否启用',
      dataIndex: 'is_active',
      render:(value,record)=>(
        <Tag color={record.is_active ? 'green':'red'}>
          {record.is_active ? '启用':'禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render:(value,record)=>(
        <>
          {dayjs(record.createdAt).format('YYYY-MM-DD')}
        </>
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      render:(value,record)=>(
        <>
          {dayjs(record.updatedAt).format('YYYY-MM-DD')}
        </>
      )
    },
    {
      title:'操作',
      render:(_,record)=>(
        <Space size="small">
          <Button type='primary' onClick={()=>handleOpenDrawer(record)}>编辑</Button>
          <Button type='dashed' onClick={()=>openDelModel(record)}>删除</Button>
        </Space>
      )
    }
  ];

  // rowSelection object indicates the need for row selection
  const rowSelection: TableProps<CompanyList>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: CompanyList[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: CompanyList) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const [list,setList ] = useState<CompanyList[]>()
  async function companyListApi(){
    // const res =await request('/api/accounts')
    // setList(res.data)
    // console.log(res)
    const res = await getCompanyListApi()
    setList(res.data)
    // console.log('res',res.data)
  }
  useEffect(()=>{
    companyListApi()
  },[])

  // 删除逻辑
  const [delShow,setDelShow] = useState(false)
  const [confirmLoading,setConfirmLoading] = useState(false)
  // const [delData,setDelData] = useState<CompanyList>()
  // bug第一次没有直接获取到delData的数据
  const lastDelDataRef = useRef<CompanyList>(undefined)

  const openDelModel = (row:CompanyList) =>{
    setDelShow(true)
    // setDelData(row)
    lastDelDataRef.current = row
    // console.log('按钮先',delData)
  }
  const handleOk = async () =>{
    setConfirmLoading(true)
    if(lastDelDataRef.current?.id){
      const res = await delCompanyItemApi(lastDelDataRef.current?.id)
      if(res.data.code === 10000){
        setConfirmLoading(false)
        setDelShow(false)
        message.info({
          type:'success',
          content:res.data.message
        })
        companyListApi()
      }
    } 
    // console.log('确认框',delData)
    // setTimeout(() => {
    //   setDelShow(false)
    //   setConfirmLoading(false)
    // }, 1500);
    // 删除返回成功
  }
  const handleCancel = () => {
    message.open({
      type:'warning',
      content:' 取消删除当前信息'
    })
    setDelShow(false)
  }
  return (
    <div>
      <Divider />
      <Table<CompanyList>
        rowSelection={{ type: 'checkbox', ...rowSelection }}
        columns={columns}
        dataSource={list}
        rowKey="id"
      />
      {/* 编辑抽屉 */}
      <DrawerItem 
        title="编辑信息"
        visible={isDrawerVisible}
        onClose={handleCloseDrawer}
        data={companyItem}
      />
      {/* 删除提示框 */}
      <Modal
        title="温馨提示"
        open={delShow}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        cancelText={'取消'}
        okText={'删除'}
        okType='primary'
      >
        <p>确定要删除当前信息吗？</p>
      </Modal>
    </div>
  );
};

export default CompanyList;